package co.edu.uniandes.entregAndes.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import co.edu.uniandes.entregAndes.fachada.EntregAndesAdmin;
import co.edu.uniandes.entregAndes.vos.EnviosValue;
import co.edu.uniandes.entregAndes.vos.VehiculosValue;

/**
 * Servlet implementation class ServletAdmin
 */
public class ServletAdmin extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static EntregAndesAdmin entregAndesAdmin = EntregAndesAdmin
			.darInstancia();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ServletAdmin() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String requerimiento = request.getParameter("requerimiento");

		if (requerimiento.equals("consultar")) {
			ArrayList<EnviosValue> resp = new ArrayList<EnviosValue>();
			String valorCriterio = "";
			if (request.getParameter("tipoCriterio").equals("ciudad_origen")
					|| request.getParameter("tipoCriterio").equals(
							"ciudad_destino")) {
				valorCriterio = request.getParameter("codPostalCiudad");
			} else {
				valorCriterio = request.getParameter("valorCriterio");
			}
			resp.addAll(entregAndesAdmin.respConsultaEnviosValueMetRF1(
					request.getParameter("tipoCriterio"), valorCriterio,
					request.getParameter("orden")));
			PrintWriter pw = response.getWriter();
			if (!resp.isEmpty()) {
				for (EnviosValue ev : resp) {
					pw.println("<b>" + ev.darId() + "</b><br>");
					pw.println("-- Estado:" + ev.darEstado());
					pw.println("<br>-- Destino:" + ev.darCiudadDestino()
							+ "<br><br>");
				}
			} else {
				pw.print("No hay");
			}
		} else if (requerimiento.equals("actualizar")) {
			try {
				entregAndesAdmin.consultaMetRF4(request
						.getParameter("datosEnvio"));
				response.getWriter().print("<html>");
				response.getWriter().print("<head></head>");
				response.getWriter().print("<body>");
				response.getWriter().println(
						"Realizado Satisfactoriamente.<br>");
				response.getWriter().println(
						"<a href=\"/EntregAndes/\">Volver</a>");
				response.getWriter().print("</body>");
				response.getWriter().print("</html>");
			} catch (Exception e) {
				response.getWriter()
						.println(
								"Serious error.\n All shortcuts have disappeared.\n Screen. Mind. Both are blank.\n\n"
										+ e.getMessage());
			}
		} else if (requerimiento.equals("modificar")) {
			try {
				entregAndesAdmin.consultaMetRF5(
						Integer.parseInt(request.getParameter("idEnvio")),
						request.getParameter("nuevaDireccion"),
						request.getParameter("codPostalCiudad"),
						request.getParameter("emailDestino"),
						request.getParameter("tipoPersona"));
				response.getWriter().println("Realizado Satisfactoriamente.");
			} catch (Exception e) {
				response.getWriter().println(e.getMessage());
			}
		} else if (requerimiento.equals("registrar")) {
			String rta = entregAndesAdmin.consultaMetRF3(
					request.getParameter("peso"),
					request.getParameter("direccionOrigen"),
					request.getParameter("direccionDestino"),
					request.getParameter("nombre_tipo"),
					request.getParameter("volumen"),
					request.getParameter("correo_remitente"),
					request.getParameter("cod_postal_origen"),
					request.getParameter("correo_destinatario"),
					request.getParameter("cod_postal_destino"),
					request.getParameter("nombre_oficina_origen"),
					request.getParameter("tipo_persona"));
			response.getWriter().print("<html>");
			response.getWriter().print("<head></head>");
			response.getWriter().print("<body>");
			response.getWriter().println(
					"Realizado Satisfactoriamente. El costo es " + rta);
			response.getWriter().print(
					"<br><a href=\"/EntregAndes/operator/\">Aceptar</a><br>");
			response.getWriter()
					.print("<form action=\"/EntregAndes/operator/process\" method=\"get\">");
			response.getWriter()
					.print("<input type=\"hidden\" id=\"requerimiento\" name=\"requerimiento\" value=\"eliminarEnvioNuevo\">");
			response.getWriter().print(
					"<button type=\"submit\">No Aceptar</button>");
			response.getWriter().print("</form>");
			response.getWriter().print("<body>");
			response.getWriter().print("</html>");
		} else if (requerimiento.equals("eliminarEnvioNuevo")) {
			try {
				entregAndesAdmin.darDao().eliminarUltimoEnvio();
				response.getWriter().print("Realizado Satisfactoriamente.");
			} catch (Exception e) {
				response.getWriter()
						.println(
								"Serious error.\n All shortcuts have disappeared.\n Screen. Mind. Both are blank.\n\n"
										+ e.getMessage());
			}
		} else if (requerimiento.equals("registrarVehiculoNuevo")) {
			try {
				entregAndesAdmin.consultaMetRF11(request.getParameter("placa"),
						request.getParameter("tipo"),
						request.getParameter("idTrayecto"));
				response.getWriter().print("<html>");
				response.getWriter().print("<head></head>");
				response.getWriter().print("<body>");
				response.getWriter().println("Realizado Satisfactoriamente.");
				response.getWriter()
						.print("<br><a href=\"/EntregAndes/operator/\">Aceptar</a><br>");
				response.getWriter().print("<body>");
				response.getWriter().print("</html>");
			} catch (Exception e) {
				response.getWriter()
						.println(
								"Serious error.\n All shortcuts have disappeared.\n Screen. Mind. Both are blank.\n\n"
										+ e.getMessage());
			}
		} else if (requerimiento.equals("sacarServicioVehiculo")) {
			try {
				String rta = entregAndesAdmin.consultaMetRF10(request
						.getParameter("placa"));
				response.getWriter().print("<html>");
				response.getWriter().print("<head></head>");
				response.getWriter().print("<body>");
				response.getWriter().println("" + rta + "<br>");
				response.getWriter()
						.print("<br><a href=\"/EntregAndes/operator/\">Aceptar</a><br>");
				response.getWriter().print("<body>");
				response.getWriter().print("</html>");
			} catch (Exception e) {
				response.getWriter()
						.println(
								"Serious error.\n All shortcuts have disappeared.\n Screen. Mind. Both are blank.\n\n"
										+ e.getMessage());
			}
		} else if (requerimiento.equals("registrarEspecial")) {
			try {
				if (request.getParameter("tipoEspecial")
						.equals("institucional")) {
					if (!request.getParameter("direccionDestino").contains(",")
							|| !request.getParameter("correo_destinatario")
									.contains(",")
							|| !request.getParameter("cod_postal_destino")
									.contains(",")) {
						throw new Exception(
								"Los datos de destino no contienen comas.");
					} else {
						try {
							entregAndesAdmin
									.consultaMetRF8(
											request.getParameter("peso"),
											Integer.valueOf(request
													.getParameter("cantidad")),
											request.getParameter("direccionOrigen"),
											request.getParameter(
													"direccionDestino").split(
													","),
											request.getParameter("nombre_tipo"),
											request.getParameter("volumen"),
											request.getParameter("correo_remitente"),
											request.getParameter("cod_postal_origen"),
											request.getParameter(
													"correo_destinatario")
													.split(","),
											request.getParameter(
													"cod_postal_destino")
													.split(","),
											request.getParameter("nombre_oficina_origen"));
							response.getWriter().print("<html>");
							response.getWriter().print("<head></head>");
							response.getWriter().print("<body>");
							response.getWriter().println(
									"Realizado Satisfactoriamente.");
							response.getWriter()
									.print("<br><a href=\"/EntregAndes/operator/\">Aceptar</a><br>");
							response.getWriter().print("<body>");
							response.getWriter().print("</html>");
						} catch (Exception e) {
							response.getWriter()
									.println(
											"Serious error.\n All shortcuts have disappeared.\n Screen. Mind. Both are blank.\n\n"
													+ e);
						}
					}
				} else {
					try {
						if (request.getParameter("direccionDestino").contains(
								",")
								|| request.getParameter("correo_destinatario")
										.contains(",")
								|| request.getParameter("cod_postal_destino")
										.contains(",")) {
							throw new Exception(
									"Lo sentimos, la informacion de destino en un envio en lote no pueden contener comas.");
						}
						entregAndesAdmin.consultaMetRF9(request
								.getParameter("peso"), Integer.valueOf(request
								.getParameter("cantidad")), request
								.getParameter("direccionOrigen"), request
								.getParameter("direccionDestino"), request
								.getParameter("nombre_tipo"), request
								.getParameter("volumen"), request
								.getParameter("correo_remitente"), request
								.getParameter("cod_postal_origen"), request
								.getParameter("correo_destinatario"), request
								.getParameter("cod_postal_destino"), request
								.getParameter("nombre_oficina_origen"), request
								.getParameter("tipo_persona"));
						response.getWriter().print("<html>");
						response.getWriter().print("<head></head>");
						response.getWriter().print("<body>");
						response.getWriter().println(
								"Realizado Satisfactoriamente.");
						response.getWriter()
								.print("<br><a href=\"/EntregAndes/operator/\">Aceptar</a><br>");
						response.getWriter().print("<body>");
						response.getWriter().print("</html>");
					} catch (Exception e) {
						response.getWriter()
								.println(
										"Serious error.\n All shortcuts have disappeared.\n Screen. Mind. Both are blank.\n\n"
												+ e);
					}
				}
			} catch (Exception e) {
				response.getWriter()
						.println(
								"Serious error.\n All shortcuts have disappeared.\n Screen. Mind. Both are blank.\n\n"
										+ e);
			}
		} else if (requerimiento.equals("porcentaje_ocupado")) {
			try {
				ArrayList<VehiculosValue> resp = entregAndesAdmin
						.respConsultaVehiculosValueMetRF43(request
								.getParameter("porcentaje"), request.getParameter("tipo_porcentaje"),request.getParameter("tipo_vehiculo"));
				PrintWriter pw = response.getWriter();
				for (VehiculosValue ev : resp) {
					pw.println("<b>" + ev.darPlaca() + "</b><br>");
					pw.println("-- Estado: " + ev.darEstado() + "<br><br>");
				}
			} catch (Exception e) {
				System.out.println(e.getMessage());
				response.getWriter()
						.println(
								"Serious error.\n All shortcuts have disappeared.\n Screen. Mind. Both are blank.\n\n"
										+ e);
			}
		} else if (requerimiento.equals("vigentes_oficina")) {
			try {
				ArrayList<String[]> resp = entregAndesAdmin
						.respConsultaVehiculosValueMetRF45(request
								.getParameter("nombreOficina"));
				PrintWriter pw = response.getWriter();
				for (String[] ev : resp) {
					pw.println("<h1> Info envio </h1><br>");
					pw.println("<b> --id: " + ev[0] + "</b><br>");
					pw.println("<b>-- estado: " + ev[2] + "</b><br>");
					pw.println("<b>--Correo Usuario Origen: " + ev[1] +" </b><br>");
					pw.println("<b> --Nombre Usuario Origen:" + ev[4]+"</b><br>");
					pw.println("<b>-- Nacionalidad Usuario Origen: "+ ev[3]+ "</b><br>");
					pw.println("<b>-- Direccion Usuario Origen: "+ ev[5]+ "</b><br>");
					pw.println("<br> Info trayecto: <br>");
					pw.println("<br>-- Id trayecto salida oficina "+ ev[6]+ "<br><br>");
				}
			} catch (Exception e) {
				response.getWriter()
						.println(
								"Serious error.\n All shortcuts have disappeared.\n Screen. Mind. Both are blank.\n\n"
										+ e);
			}
		} else {
			response.getWriter()
					.println(
							"Serious error.\n All shortcuts have disappeared.\n Screen. Mind. Both are blank.");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}
}
